import { Injectable } from '@angular/core';

import { AppCommConfig, AppInitConfig } from './interface';

/**
 * 全局注册，用于保存应用的基本信息，不依赖delon的theme/settring
 */
@Injectable({ providedIn: 'root' })
export class AppConfigService {
    private _appInitConfig!: AppInitConfig;

    private _appCommConfig?: AppCommConfig;

    get appInitUrl(): string {
        return `${this._appInitConfig.appInitServer}/app/list/getAppInfo?_allow_anonymous=true` + `&appId=${this._appInitConfig.appId}`;
    }

    constructor() {
        this.getAssetConfig(`assets/config/app-config.json?rand=${Math.random()}`, (res: any) => {
            this._appInitConfig = res;
        });
    }

    public setAppCommConfig(config: AppCommConfig): void {
        this._appCommConfig = config;
    }

    public get appApiHost(): string {
        return this._appInitConfig?.apiUrl || '';
    }

    public getHelpDocUrl(): string {
        return this._appCommConfig?.helpDocUrl || '';
    }

    public getPublicKey(): string {
        return this._appCommConfig?.publicKey || '';
    }

    public getAppCommConfig(): AppCommConfig | undefined {
        return this._appCommConfig;
    }

    /**
     * 获取是否加密密码
     */
    public getIsEncryptPW(): boolean {
        return this._appCommConfig?.encryptPW || false;
    }

    /**
     * 同步获取本地静态文件
     * @param url string
     * @param callback void
     */
    getAssetConfig(url: string, callback: any): any {
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    let result = {} as any;
                    try {
                        result = JSON.parse(xhr.responseText);
                    } catch (e) {
                        console.error(e);
                    }
                    // tslint:disable-next-line: no-unused-expression
                    callback && callback(result);
                }
            }
        };
        xhr.open('GET', url, false);
        xhr.send(null);
    }
}
